from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
from django.conf import settings
# def test(request):
#     print(request.method)
#     obj=JsonResponse({'name':'lqz','age':18})
#     # # 只针对域简单请求
#     # # obj['Access-Control-Allow-Origin']='*'
#     # print(request.META)
#     # if request.method=='OPTIONS':
#     #     obj['Access-Control-Allow-Headers'] = 'Content-Type,authorization'
#     #     # obj['Access-Control-Allow-Headers'] = '*'
#     # obj['Access-Control-Allow-Origin']='http://127.0.0.1:8001'
#     # # obj['Access-Control-Allow-Origin']='*'
#     return obj
#
#
#
#
#
#
def test2(request):
    print(request.method)
    return JsonResponse({'name':'lqz333','age':18})


# 自动生成路由，post请求，数据库操作
from rest_framework.viewsets import ViewSet
from rest_framework.decorators import action
from . import serializer

from utils.response import APIResponse
# 自动生成路由
from rest_framework.viewsets import ViewSetMixin, ViewSet
from rest_framework.views import APIView
import re

from lib.t_sms import get_code, send_code

from django.core.cache import cache
from . import models


class LoginView(ViewSet):
    @action(methods=['post', ], detail=False)
    def login(self, request, *args, **kwargs):
        ser = serializer.LoginSerialzer(data=request.data, context={'request': request})
        if ser.is_valid():
            token = ser.context['token']
            user = ser.context['user']
            icon = ser.context['icon']
            return APIResponse(token=token, username=user.username, icon=icon, id=user.id)
        else:
            return APIResponse(status=1, msg='用户名或密码错误')

    @action(methods=['get', ], detail=False)
    def check_mobile(self, request, *args, **kwargs):
        mobile = request.GET.get('mobile')
        # 手机号是否合法（是不是一个手机号）
        import re
        if re.match(r'^1[3-9][0-9]{9}$', mobile):
            # 查询手机号是否存在
            user = models.User.objects.filter(mobile=mobile).first()
            if user:
                return APIResponse(msg='手机号存在')
            else:
                return APIResponse(status=1, msg='手机号未注册')
        else:
            return APIResponse(status=2, msg='手机号不合法')


# class SendCodeView(ViewSetMixin,APIView):
class SendCodeView(ViewSet):
    @action(methods=['get', ], detail=False)
    def send_code(self, request, *args, **kwargs):
        mobile = request.GET.get('mobile')
        # 1验证手机号是否合法
        if re.match(r'^1[3-9][0-9]{9}$', mobile):
            # 2 生成验证码
            code = get_code()
            print(code)
            # 3发送验证码
            res, msg = send_code(mobile, code)
            if res:
                # 4发送成功，验证码保存（保存在哪），原来保存到session中
                # 存到缓存中，
                # cache.set('',code,60*3)
                # sms_cache_18953666666  缓存时间  3分钟
                cache.set(settings.SMS_CACHE_KEY % {'mobile': mobile}, code, settings.SMS_CACHE_TIME)
                return APIResponse(msg=msg)
            else:
                return APIResponse(status=1, msg=msg)
        else:
            return APIResponse(status=1, msg='手机号不合法')
        # 5返回给前端信息

    @action(methods=['post', ], detail=False)
    def code_login(self, request, *args, **kwargs):
        ser = serializer.LoginCodeSerialzer(data=request.data, context={'request': request})
        if ser.is_valid():
            token = ser.context['token']
            user = ser.context['user']
            icon = ser.context['icon']
            return APIResponse(token=token, username=user.username, icon=icon, id=user.id)
        else:
            return APIResponse(status=1, msg=ser.errors)


# 自动生成路由，跟数据打交道，create方法
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import CreateModelMixin
from rest_framework.viewsets import GenericViewSet


# class CodeRegister(ViewSetMixin,GenericAPIView,CreateModelMixin):
class CodeRegister(GenericViewSet, CreateModelMixin):
    queryset = models.User.objects.all()
    serializer_class = serializer.CodeRegisterSerializer

    def create(self, request, *args, **kwargs):
        res = super().create(request, *args, **kwargs)
        return APIResponse(msg='注册成功', username=res.data.get('username'), mobile=res.data.get('mobile'))


from utils.redis_pool import POOL
import redis


def test_redis(request):
    conn = redis.Redis(connection_pool=POOL)
    age = str(conn.get('age'), encoding='utf-8')

    return HttpResponse('人的年龄，从redis中取出来了是：%s' % age)


from django_redis import get_redis_connection


def test_django_redis(request):
    # 从连接池中拿到连接
    conn = get_redis_connection()

    age = str(conn.get('age'), encoding='utf-8')

    from django.core.cache import cache
    cache.set('name', 'lqz', 4)  # 往缓存中放key和value，其实放到了redis中了

    cache.set('xxx', test_redis)
    return HttpResponse('人的年龄是：%s' % age)


from celery_task import user_task
from celery_task.celery import app
from celery.result import AsyncResult


def test_celery(request):
    res_id = request.GET.get('id')
    if res_id:
        res = AsyncResult(id=res_id, app=app)
        if res.successful():
            result = res.get()
            print(result)
            return HttpResponse('执行完成了，结果是：%s' % result)

    res = user_task.send_sms.delay('18276345221')
    return HttpResponse('任务号是：%s' % str(res))
